package com.mitu.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Arrays;

/**
 * 1. Scattering:将数据写入buffer时，可以采用Buffer数组，依次写入
 * 2. Gathering:将数据从buffer中读取数据时可以采用Buffer数组，并依次读取
 */
public class ScatteringAndGatheringTest {
    public static void main(String[] args) throws IOException {
        //使用ServerSocketChannel和SocketChannel
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        InetSocketAddress inetSocketAddress = new InetSocketAddress(7000);
        //绑定端口到socket,并启动
        serverSocketChannel.socket().bind(inetSocketAddress);
        //创建一个Buffer数组
        ByteBuffer[] byteBuffers = new ByteBuffer[2];
        byteBuffers[0] = ByteBuffer.allocate(5);
        byteBuffers[1] = ByteBuffer.allocate(3);
        //等待客户端连接(telnet)
        SocketChannel socketChannel = serverSocketChannel.accept();
        int meessageLength = 8;   //假定从客户端接收8个字节
        //循环读取
        while (true) {
            int byteRead = 0;
            while (byteRead < meessageLength) {
                long i = socketChannel.read(byteBuffers);
                byteRead += i;
                System.out.println("byRead=" + byteRead);
                //使用流打印,查看当前Buffer的position和limit
                Arrays.asList(byteBuffers).stream().map(buffer -> "position=" +
                        buffer.position() + ",limit=" +
                        buffer.limit()).forEach(System.out::println);
            }

            //将所有的buffer进行切换读写模式
            Arrays.asList(byteBuffers).forEach(byteBuffer -> byteBuffer.flip());
            //将数据读出然后显示到客户端
            long byteWrite = 0;
            while (byteWrite < meessageLength) {
                long k = socketChannel.write(byteBuffers);   //回送
                byteWrite += k;
            }

            //将所有的buffer清空
            Arrays.asList(byteBuffers).forEach(byteBuffer -> {
                byteBuffer.clear();
            });
            System.out.println("byteRead:=" + byteRead +
                    ",byteWrite:=" + byteWrite +
                    ",messageLength" + meessageLength);

        }

    }
}
